package com.czm.art_light.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czm.art_light.annotation.CacheWithLock;
import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.constant.CommonConsts;
import com.czm.art_light.constant.RedisConstant;
import com.czm.art_light.entity.ArtArtist;
import com.czm.art_light.entity.ArtMovement;
import com.czm.art_light.entity.ArtTopic;
import com.czm.art_light.entity.ArtWork;
import com.czm.art_light.exception.BusinessException;
import com.czm.art_light.mapper.ArtArtistMapper;
import com.czm.art_light.mapper.ArtTopicMapper;
import com.czm.art_light.mapper.ArtWorkMapper;
import com.czm.art_light.param.request.ArtInfoReqDto;
import com.czm.art_light.param.request.ArtSearchReqDto;
import com.czm.art_light.param.request.ArtWorkReqDto;
import com.czm.art_light.param.request.PageReqDto;
import com.czm.art_light.param.response.*;
import com.czm.art_light.service.ArtTopicService;
import jakarta.validation.Valid;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 话题信息 服务类
 */
@Service
public class ArtTopicServiceImpl implements ArtTopicService {

    @Autowired
    private ArtTopicMapper artTopicMapper;

    @Autowired
    private ArtWorkMapper artWorkMapper;

    @Autowired
    private ArtArtistMapper artArtistMapper;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 根据话题id和分页信息查找对应的话题信息
     */
    @CacheWithLock(
            cacheName = "artTopicCache",
            key = "#artInfoReqDto.id + '::' + #artInfoReqDto.pageNum + '::' + #artInfoReqDto.pageSize",   //从参数对象提取属性
            expireTime = CommonConsts.TOPIC_CACHE_EXPIRATION_TIME,
            cacheNull = true,
            enabled = true
    )
    @Override
    public ArtInfoRespDto getById(ArtInfoReqDto artInfoReqDto) {
        // 判断布隆过滤器中是否存在数据
        RBloomFilter<Integer> rBloomFilter = redissonClient.getBloomFilter(RedisConstant.ART_TOPIC_BLOOM_FILTER_KEY);
        //不存在直接返回null
        if (!rBloomFilter.contains(artInfoReqDto.getId())) {
            return null;
        }

        ArtTopic artTopic = artTopicMapper.getById(artInfoReqDto.getId());
        // 话题不存在
        if (artTopic == null) {
            throw new BusinessException(ArtErrorCodeEnum.TOPIC_NOT_EXIST);
        }

        //构建分页对象
        Page<ArtWorkBasicInfoRespDto> page = new Page<>(artInfoReqDto.getPageNum(), artInfoReqDto.getPageSize());
        //根据话题id查找对应的艺术家
        ArtWorkReqDto artWorkReqDto = new ArtWorkReqDto();
        artWorkReqDto.setTopicId(artInfoReqDto.getId());
        //根据话题id查找所有的艺术家id
        List<Integer> artistIdList = artWorkMapper.listArtArtistIdByParamId(page, artWorkReqDto);
        //再根据查找到的艺术家id查找对应的艺术家基本信息
        List<ArtArtistBasicInfoRespDto> artists = new ArrayList<>();
        if (!artistIdList.isEmpty()) {
            for (Integer id : artistIdList) {
                //根据艺术家id查找对应的艺术家基本信息
                ArtArtistBasicInfoRespDto artArtistBasicInfoRespDto = artArtistMapper.artistBasicInfogetById(id);
                artists.add(artArtistBasicInfoRespDto);
            }
        }

        //根据话题id查找对应的艺术作品数据
        List<ArtWork> workList = artWorkMapper.listArtWorkByParamId(page, artWorkReqDto);
        List<ArtWorkBasicInfoRespDto> artworks = new ArrayList<>();
        if (!workList.isEmpty()) {
            for (ArtWork work : workList) {
                artworks.add(ArtWorkBasicInfoRespDto.builder()
                        //作品id
                        .id(work.getId())
                        //作品名称
                        .title(work.getTitle())
                        //艺术家名称
                        .artistName(artArtistMapper.getById(work.getArtistId()).getArtistName())
                        //作品图片
                        .primaryImageSmallUrl(work.getPrimaryImageSmallUrl())
                        .build());
            }
        }

        return ArtInfoRespDto.builder()
                //话题id
                .id(artTopic.getId())
                //话题名称
                .name(artTopic.getTopicName())
                //话题图片
                .imageUrl(artTopic.getBackgroundImageUrl())
                //话题简介
                .description(artTopic.getTopicDescription())
                //艺术家列表
                .artists(artists)
                //艺术作品列表
                .artworks(artworks)
                .build();
    }

    /**
     * 获取所有的话题基本信息
     */
    @Override
    public List<ArtTopicBasicInfoRespDto> list(PageReqDto pageReqDto) {
        List<ArtTopicBasicInfoRespDto> allTopics = new ArrayList<>();

        if (pageReqDto.isFetchAll()) {
            // 如果 fetchAll 为 true，则查询所有数据，忽略分页
            List<ArtTopic> artTopicList = artTopicMapper.selectAllWithoutPage();
            for (ArtTopic artTopic : artTopicList) {
                allTopics.add(ArtTopicBasicInfoRespDto.builder()
                        //话题id
                        .id(artTopic.getId())
                        //话题名字
                        .topicName(artTopic.getTopicName())
                        .build());
            }
        } else {
            // 如果 fetchAll 为 false，则使用分页查询
            Page<ArtTopicBasicInfoRespDto> page = new Page<>(pageReqDto.getPageNum(), pageReqDto.getPageSize());
            allTopics = artTopicMapper.selectAll(page);
        }

        // 返回结果，如果无数据，返回空列表
        return allTopics == null ? Collections.emptyList() : allTopics;
    }
}
